<?php

function trim_str($str) {
    if (empty($str)) {
        return "";
    }
    return str_replace("\r\n", "", trim($str));
}

$src_file_name = "xmarks.json";
$src_file_content = file_get_contents($src_file_name);
$src_json = json_decode($src_file_content);
$list = $src_json->{"commands"}->{"set"};
$result = array();
foreach ($list as $one) {
    $sub = $one->{"args"};
    $element = array();
    $element_args = array();

//    $element["action"] = $one->{"action"};
    $element["title"] = trim_str($sub->{"name"});
    $element["id"] = $one->{"nid"};
    $element["parent"] = $sub->{"pnid"};
//    $element["dateAdded"] = $sub->{"created"};
//    $element["lastModified"] = $sub->{"modified"};

    if ($sub->{"pnid"} == "ROOT") {
        $element["annos"] = $element_args;
        $result[] = $element;
    } else {
        $element["uri"] = $sub->{"url"};
        $i = 0;
        foreach ($result as $categray) {
            $i++;
            if ($categray["id"] == $sub->{"pnid"}) {
                $result[$i]["children"][] = $element;
                //$categray["children"][] = $element;
            }
        }
    }
}
//var_dump($result);
echo json_encode($result);
?>